import React, {useRef, useState,useCallback} from "react";
import Qmap,{ queryAddress,queryLocation }  from 'react-qqmap';
import {LdhButton, LdhInput, Message} from "./Components";
import {Col, Row} from "antd";

const KEY = "GQIBZ-5ZFWV-ZPLPQ-5X7FZ-P67I6-2PFOB";
const DEFAULT_CENTER ={lng: 120.129295, lat: 30.301348}
/**
 * pos: 原始位置
 * onPosChange: 位置变化事件，传递位置信息 {province, city, street, street, lat, lng}
 * @param props
 * @returns {*}
 * @constructor
 */
const Map = (props)=>{
    const QmapRef = useRef();
    const [address, setAddress] = useState("杭州汽车西站");
    let {onPosChange, originPos, ...rest} = props;
    const [options, setOptions] = useState({center:originPos||DEFAULT_CENTER,zoom:16});
    let [pos, setPos] = useState({});
    const getLatLng = useCallback((location) => {
        const LatLng = new QmapRef.current.constructor.LatLng(
            location?.lat || 39.908802,
            location?.lng || 116.397502,
        );

        return LatLng;
    }, []);
    const addMarker = useCallback((title, location) => {
        const position = getLatLng(location);
        QmapRef.current.instance.setCenter(position);
        QmapRef.current.marker.add([
            {id: title,styleId: 'marker', position},
        ]);
    }, []);
    const removeMarker = useCallback((title) => {
        QmapRef.current.marker.remove([title]);
    }, []);


    // 进行查询
    const handleSearch =()=>{
        queryLocation({
            key: KEY,
            address,
        }).then((res) => {
            if(res.status!=0){
                Message.warning(res.message);
                return;
            }
            let {result:{address_components, location}} = res;
            let {province, city, district} = address_components;
            Message.info(`${province} ${city} ${district}`);
            // 响应结果: res 同 参考文档-响应结果
            let {lat, lng} =location;

            removeMarker("POS");
            addMarker("POS", location)
            setOptions({center:location});

            queryAddress({key:KEY,location}).then(res=>{
                let street = res.result.address_component.street_number;
                let address = `${province} ${city} ${district} ${street}`;
                let pos={lat,lng,province, city, district,street, address};
                setPos(pos);
                onPosChange && onPosChange(pos);
            });

        });
    }

    return <div>
        <Row className="mb-5">
            <Col span={20}>
                <LdhInput value={address} onChange={(e)=>setAddress(e.target.value)}/>

            </Col>
            <Col span={4}>
                <LdhButton onClick={handleSearch} type="primary" className="h-40">查询</LdhButton>
            </Col>
        </Row>
        <div className="flex-between">
            <div>地址：<b>{pos.address}</b></div>
            <div>纬度：<b>{pos.lat}</b> 经度：<b>{pos.lng}</b></div>
        </div>
        <Qmap id="container" API_GL_KEY={KEY}  options={options} {...rest}
              onInit={({ constructor, instance, marker }) => {
                  QmapRef.current = {
                      constructor, // 即 TMap
                      instance, // 地图实例
                      marker, // 点标记实例
                  };
                  let c =DEFAULT_CENTER;//options.center;
                  let center = new constructor.LatLng(c.lat, c.lng);

                  //let map = new constructor.Map("container", {center});

                  let infoWindow = new constructor.InfoWindow({
                      map: instance,
                      position: center, //设置信息框位置
                      content: 'Hello World!', //设置信息框内容

                  });
                  instance.on("click", (e)=>{
                      infoWindow.close();
                      infoWindow.setPosition(e.latLng);
                      queryAddress({key:KEY,location:e.latLng}).then(res=>{
                          let {formatted_addresses, address_component} =res.result;
                          let name = formatted_addresses.recommend;

                          let {province, city, district, street} = address_component
                          let {lat, lng} = e.latLng;
                          let address = `${province} ${city} ${district} ${street}`;
                          let pos={lat,lng,province, city, district,street, address};
                          setPos(pos);
                          onPosChange && onPosChange(pos);
                          infoWindow.setContent(`<b>${name}</b><div>${address}</div><div style="font-size: 12px; color: #999">${lat} / ${lng}</div>`)
                          infoWindow.open();
                      });

                  })


              }}>

        </Qmap>
    </div>
}
export default Map;